<template>
  <div class="tree-nav-container">
    <div class="search-box">
      <div class="product-title">产品组件</div>
      <img
        class="file-add"
        src="@/assets/images/fileAdd.png"
        alt="文件添加"
        @click="handleAdd"
      />
    </div>

    <div class="product-input">
      <el-input
        v-if="showProductInput"
        v-model="productValue"
        @blur="handleBlur"
        placeholder="请输入"
        class="search-input"
      />
    </div>

    <el-tree
      ref="treeRef"
      class="nav-tree"
      :data="filteredData"
      node-key="id"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>
            <span v-html="getIcon(data.folderType)"></span>
            <span v-if="!data.editing">{{ node.label }}</span>
            <span v-else>
              <el-input
                v-model="node.label"
                ref="editInputRef"
                size="small"
                @blur="handleEditBlur(node, data)"
                @keyup.enter="handleEditBlur(node, data)"
              />
            </span>
          </span>
          <div>
            <el-dropdown
              trigger="click"
              @command="(command) => handleCommand(command, node, data)"
            >
              <span class="el-dropdown-link"> ... </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="['ROOTDIRECTORY', 'NORMALDIRECTORY'].includes(data.folderType)"
                    :icon="Plus"
                    command="newFile"
                    >新建文件夹</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="['ROOTDIRECTORY', 'NORMALDIRECTORY'].includes(data.folderType)"
                    :icon="Plus"
                    command="newProduct"
                    >新建产品</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="['ROOTDIRECTORY', 'NORMALDIRECTORY'].includes(data.folderType)"
                    :icon="Upload"
                    command="batchImport"
                    >批量导入</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="['PRODUCT', 'SUBPRODUCTS'].includes(data.folderType)"
                    :icon="Plus"
                    command="newSubProduct"
                    >新建子产品</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="data.folderType"
                    :icon="EditPen"
                    command="rename"
                    >重命名</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="data.folderType"
                    :icon="Delete"
                    command="remove"
                  >
                    <el-popconfirm
                      title="确定要删除吗?"
                      @confirm="handleDelete(node, data)"
                      @click.stop
                    >
                      <template #reference>
                        <span @click.stop style="width: 80%">删除</span>
                      </template>
                    </el-popconfirm>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="data.folderType != 'NORMALDIRECTORY'"
                    :icon="DocumentCopy"
                    command="copyProduct"
                    >{{
                      data.folderType == "ROOTDIRECTORY" ? "复制文件夹" : "复制产品"
                    }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <!-- 添加子节点输入框 -->
        <!-- <div v-if="data.showInput" class="add-input-container">
          <el-input
            ref="childInputRef"
            v-model="newChildName"
            size="small"
            placeholder="输入子节点名称"
            @blur="confirmAddChild(node, data)"
            @keyup.enter="confirmAddChild(node, data)"
          />
        </div> -->
      </template>
    </el-tree>
  </div>
</template>

<script setup>
    import { ref, computed, watch } from "vue";
    import {
      CirclePlusFilled,
      Plus,
      InfoFilled,
      CirclePlus,
      Check,
      Upload,
      EditPen,
      Delete,
      DocumentCopy,
    } from "@element-plus/icons-vue";
    //产品组件库值
    const productValue = ref("");
    const showProductInput = ref(false);
    // 树形数据
    const dataSource = ref([
      {
        id: 1458,
        label: "建筑类",
        depth: 1,
        folderType: "ROOTDIRECTORY",
        children: [
          {
            id: 1460,
            label: "建筑材料",
            depth: 2,
            folderType: "NORMALDIRECTORY",
            children: [
              {
                id: 1461,
                label: "大理石",
                depth: 3,
                folderType: "PRODUCT",
                modelingType: "STAGEMODELING",
              },
              {
                id: 1468,
                label: "钢筋",
                depth: 3,
                folderType: "PRODUCT",
                modelingType: "STAGEMODELING",
              },
              {
                id: 1480,
                label: "测试",
                depth: 3,
                folderType: "PRODUCT",
                modelingType: "STAGEMODELING",
              },
            ],
          },
          {
            id: 1581,
            label: "水泥",
            depth: 2,
            folderType: "PRODUCT",
            modelingType: "STAGEMODELING",
          },
        ],
      },
      {
        id: 5481,
        label: "俄武器",
        depth: 1,
        folderType: "ROOTDIRECTORY",
        children: [
          {
            id: 5482,
            label: "测试003",
            depth: 2,
            folderType: "PRODUCT",
            modelingType: "STAGEMODELING",
            children: [
              {
                id: 5483,
                label: "测试004",
                depth: 3,
                folderType: "SUBPRODUCTS",
                modelingType: "STAGEMODELING",
                children: [
                  {
                    id: 5485,
                    label: "测试005",
                    depth: 4,
                    folderType: "SUBPRODUCTS",
                    modelingType: "STAGEMODELING",
                    children: [
                      {
                        id: 5486,
                        label: "测试006",
                        depth: 5,
                        folderType: "SUBPRODUCTS",
                        modelingType: "STAGEMODELING",
                        children: [
                          {
                            id: 5487,
                            label: "测试007",
                            depth: 6,
                            folderType: "SUBPRODUCTS",
                            modelingType: "STAGEMODELING",
                          },
                        ],
                      },
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ]);

    // Element Tree 配置
    const defaultProps = { children: "children", label: "label" };

    // 搜索文本
    const searchText = ref("");
    const treeRef = ref(null);

    // 处理编辑完成
    const handleEditBlur = (node, data) => {
      if (data.editName && data.editName.trim() !== data.productName) {
        data.productName = data.editName.trim();
        data.updateTime = new Date().toISOString();
        emit("update:treeData", [...props.treeData]);
      }
      data.editing = false;
    };

    // 提取过滤逻辑到单独函数，提高复用性
    const isMatch = (label, keyword) => label.toLowerCase().includes(keyword);

    //新增产品组件
    const handleAdd = () => {
      showProductInput.value = true;
    };

    //产品组件库失去焦点
    const currentEditingNode = ref(null);
    const handleCommand = (command, node, data) => {
      switch (command) {
        case "newProduct":
          console.log("新增产品", command, node, data);
          currentEditingNode.value = data;
          showProductInput.value = true;
          productValue.value = "";
          break;

        case "newFile":
          currentEditingNode.value = data;
          showProductInput.value = true;
          productValue.value = "";
          // 移除未定义变量 isAddingRoot
          // 假设使用正确的展开节点方法，这里以 setCurrentKey 为例，可根据实际文档调整
          nextTick(() => {
            treeRef.value?.setCurrentKey(data.id);
          });
          break;

        case "rename":
          data.editing = true;
          nextTick(() => {
            treeRef.value?.setCurrentKey(data.id);
          });
          break;

      }

    };
    // 抽离图标逻辑到函数
    const getIcon = (folderType) => {
      if (folderType === "PRODUCT") {
        return `<svg t="1747624072282" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4557" width="14" height="14"><path d="M519.68 43.52L112 278.4v471.04l407.68 234.88 407.68-234.88V278.4L519.68 43.52z" fill="#FFFFFF" p-id="4558"></path><path d="M519.68 1016.32a26.88 26.88 0 0 1-15.36-4.48l-407.68-235.52a30.08 30.08 0 0 1-16-26.88V278.4a30.08 30.08 0 0 1 16-26.88L504.32 16a30.72 30.72 0 0 1 31.36 0l407.68 235.52a30.72 30.72 0 0 1 15.36 26.88v471.04a30.72 30.72 0 0 1-15.36 26.88l-407.68 235.52a28.8 28.8 0 0 1-16 4.48z m-375.68-285.44l375.68 217.6 376.32-217.6V296.96L519.68 80 144 296.96z" fill="#323333" p-id="4559"></path><path d="M112 278.4l407.68 231.04" fill="#FFFFFF" p-id="4560"></path><path d="M519.68 540.8a28.16 28.16 0 0 1-15.36-4.48l-407.68-230.4a31.36 31.36 0 0 1-12.16-42.88 32.64 32.64 0 0 1 43.52-12.16l407.04 231.04a31.36 31.36 0 0 1-15.36 58.88z" fill="#323333" p-id="4561"></path><path d="M916.48 283.52l-407.68 230.4" fill="#FFFFFF" p-id="4562"></path><path d="M512 545.28a31.36 31.36 0 0 1-15.36-58.88L901.12 256a31.36 31.36 0 0 1 42.88 12.16 32 32 0 0 1-12.16 42.88l-407.68 230.4a32 32 0 0 1-12.16 3.84z" fill="#323333" p-id="4563"></path><path d="M519.68 1000.96a31.36 31.36 0 0 1-31.36-31.36V501.12a31.36 31.36 0 1 1 64 0v468.48a31.36 31.36 0 0 1-32.64 31.36z" fill="#323333" p-id="4564"></path></svg>`;
      } else if (folderType === "SUBPRODUCTS") {
        return `<svg t="1747624406869" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7817" width="16" height="16"><path d="M762 744H323.6c-20.2 0-40.6-0.9-60.8 0h-0.9l18 18v-49.8-119.5-144.1-125c0-20.2 0.9-40.6 0-60.8v-0.9l-18 18h438.4c20.2 0 40.6 0.9 60.8 0h0.9l-18-18v438.4c0 20.2-0.5 40.5 0 60.8v0.9c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18v-49.8-119.5-144.1-125c0-20.2 0.5-40.5 0-60.8v-0.9c0-9.7-8.2-18-18-18H323.6c-20.2 0-40.5-0.5-60.8 0h-0.9c-9.7 0-18 8.2-18 18v438.4c0 20.2-0.5 40.5 0 60.8v0.9c0 9.7 8.2 18 18 18h438.4c20.2 0 40.5 0.5 60.8 0h0.9c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18z" p-id="7818"></path><path d="M762 350h63" fill="#FFFFFF" p-id="7819"></path><path d="M762 368h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7820"></path><path d="M762 458h63" fill="#FFFFFF" p-id="7821"></path><path d="M762 476h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7822"></path><path d="M762 566h63" fill="#FFFFFF" p-id="7823"></path><path d="M762 584h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7824"></path><path d="M762 674h63" fill="#FFFFFF" p-id="7825"></path><path d="M762 692h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7826"></path><path d="M662 644H361.9l18 18V560.2 399.1v-37.2l-18 18H662l-18-18V662c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18V560.2 399.1v-37.2c0-9.7-8.2-18-18-18H361.9c-9.7 0-18 8.2-18 18V662c0 9.7 8.2 18 18 18H662c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18z" p-id="7827"></path><path d="M199 350h63" fill="#FFFFFF" p-id="7828"></path><path d="M199 368h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7829"></path><path d="M199 458h63" fill="#FFFFFF" p-id="7830"></path><path d="M199 476h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7831"></path><path d="M199 566h63" fill="#FFFFFF" p-id="7832"></path><path d="M199 584h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7833"></path><path d="M199 674h63" fill="#FFFFFF" p-id="7834"></path><path d="M199 692h63c9.4 0 18.4-8.3 18-18-0.4-9.8-7.9-18-18-18h-63c-9.4 0-18.4 8.3-18 18 0.4 9.8 7.9 18 18 18z" p-id="7835"></path><path d="M350 262v-63" fill="#FFFFFF" p-id="7836"></path><path d="M368 262v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7837"></path><path d="M458 262v-63" fill="#FFFFFF" p-id="7838"></path><path d="M476 262v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7839"></path><path d="M566 262v-63" fill="#FFFFFF" p-id="7840"></path><path d="M584 262v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7841"></path><path d="M674 262v-63" fill="#FFFFFF" p-id="7842"></path><path d="M692 262v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7843"></path><path d="M350 825v-63" fill="#FFFFFF" p-id="7844"></path><path d="M368 825v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7845"></path><path d="M458 825v-63" fill="#FFFFFF" p-id="7846"></path><path d="M476 825v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7847"></path><path d="M566 825v-63" fill="#FFFFFF" p-id="7848"></path><path d="M584 825v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7849"></path><path d="M674 825v-63" fill="#FFFFFF" p-id="7850"></path><path d="M692 825v-63c0-9.4-8.3-18.4-18-18-9.8 0.4-18 7.9-18 18v63c0 9.4 8.3 18.4 18 18 9.8-0.4 18-7.9 18-18z" p-id="7851"></path></svg>`;
      } else if (folderType === "ROOTDIRECTORY") {
        return `<svg t="1747625546487" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9879" width="16" height="16"><path d="M919.68 951.68H104.32a96 96 0 0 1-96-96V169.6a96 96 0 0 1 96-96H384a94.08 94.08 0 0 1 72.96 33.92l56.96 64a31.36 31.36 0 0 0 24.32 10.88l379.52-3.84a97.28 97.28 0 0 1 96.64 96.64v576a96.64 96.64 0 0 1-94.72 100.48zM104.32 137.6a32 32 0 0 0-32 32v686.08a32 32 0 0 0 32 32h815.36a32.64 32.64 0 0 0 32.64-32v-576a32.64 32.64 0 0 0-32.64-32.64l-378.88 3.84a88.32 88.32 0 0 1-73.6-35.84l-56.32-64A33.92 33.92 0 0 0 384 137.6z" fill="#323333" p-id="9880"></path></svg>`;
      }
      return "";
    };
    const handleBlur = () => {
      console.log("失去焦点", productValue.value);
      if (productValue.value) {
        if (currentEditingNode.value) {
          if (!currentEditingNode.value.children) {
            currentEditingNode.value.children = [];
          }
          currentEditingNode.value.children.push({
            id: Date.now(),
            label: productValue.value,
            depth: (currentEditingNode.value.depth || 0) + 1,
            folderType: "PRODUCT",
            modelingType: "STAGEMODELING",
          });
          currentEditingNode.value = null;
        } else {
          dataSource.value.push({
            id: Date.now(),
            label: productValue.value,
          });
        }
        productValue.value = "";
        showProductInput.value = false;
      }
    };
    // 树节点点击事件
    const handleNodeClick = (node) => {
      console.log("节点", node);
    };
    // 树数据过滤方法
    const filterTreeData = (data, keyword) => {
      return data.filter((item) => {
        if (item.children) {
          item.children = filterTreeData(item.children, keyword);
        }
        return isMatch(item.label, keyword) || item.children?.length > 0;
      });
    };

    // 过滤后的数据
    const filteredData = computed(() => {
      return searchText.value
        ? filterTreeData([...dataSource.value], searchText.value.toLowerCase())
        : dataSource.value;
    });

    // Element Tree 的过滤方法
    const filterNode = (value, data) => !value || isMatch(data.label, value);

    // 监听搜索文本变化
    watch(searchText, (val) => treeRef.value?.filter(val));

    // 清空搜索
    const handleSearchClear = () => (searchText.value = "");

    const handleDelete = (node, data) => {
      console.error("删除操作缺少有效的数据或 id", node, data);
      if (!data || !data.id) {
        // console.error("删除操作缺少有效的数据或 id");
        return;
      }
      console.log("删除", node, data);
      const deleteNode = (parent, targetId) => {
        for (let i = 0; i < parent.length; i++) {
          if (parent[i].id === targetId) {
            parent.splice(i, 1);
            return true;
          }
          if (parent[i].children) {
            if (deleteNode(parent[i].children, targetId)) {
              return true;
            }
          }
        }
        return false;
      };
      deleteNode(dataSource.value, data.id);
    };

</script>

<style scoped lang="scss">
  .tree-nav-container {
    width: 250px;
    height: 100%;
    //border-right: 1px solid #eaeaea;
    background: #fff;
    display: flex;
    flex-direction: column;
  }

  .search-box {
    padding: 10px;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    justify-content: space-between;
    .product-title {
      font-size: 16px;
      font-weight: bold;
    }
    .file-add {
      width: 25px;
      height: 25px;
      cursor: pointer;
    }
  }

  .product-input {
    margin: 10px;
    ::v-deep {
      .el-input__wrapper {
        background: #f5f5f5;
      }
    }
  }

  .nav-tree {
    flex: 1;
    overflow-y: auto;
    padding: 0 10px;
    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .el-tree-node {
      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
      }
      .el-dropdown {
        .el-dropdown-link {
          color: #43bb67 !important;
          font-size: 20px;
          font-weight: bold;
        }
      }
    }
  }

  .node-label {
    margin-left: 5px;
  }

  /* 调整复选框样式 */
  :deep(.el-tree-node__content) {
    height: 36px;
  }

  /* 搜索框样式调整 */
  :deep(.el-input__wrapper) {
    box-shadow: none !important;
    border-radius: 4px;
  }
</style>
